package com.example.backend.controller;

import com.example.backend.entity.ProductListing;
import com.example.backend.service.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/seller")
public class SellerController {
    /**
     * 卖家
     * 注册《，登录《，提交资质《，修改密码《，上架商品信息《，修改上架信息《，删除上架信息《，发货《，售后（退换货）
     */
    final static int accountType = 1;

    @Autowired
    private SellerService sellerService;








    //注册
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String passWordF = credentials.get("passWordF");
        String passwordS = credentials.get("passwordS");
        String qualificationContent = credentials.get("qualificationContent");
        Map<String, Object> resp = new HashMap<>();
        //判断密码是否为空
        if (username == null || passWordF == null || passwordS == null || qualificationContent == null) {
            resp.put("message", "输入不能为空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        if (!passwordS.equals(passWordF)) {
            resp.put("message", "密码不一致");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        String result = sellerService.register(username, passWordF, passwordS, qualificationContent, accountType);
        if ("用户已存在".equals(result)) {
            resp.put("message", "用户已存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        resp.put("message", result);
        return ResponseEntity.ok(resp);
    }

    //登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials, HttpServletResponse response) {
        String accountId = credentials.get("accountId");
        String password = credentials.get("password");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || password == null) {
            resp.put("message", "accountId and password are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        // 调用登录服务
        String result = sellerService.login(accountId, password, accountType);

        if ("登录成功".equals(result)) {
            // 登录成功，设置Cookie
            jakarta.servlet.http.Cookie accountCookie = new jakarta.servlet.http.Cookie("accountId", accountId);
            accountCookie.setMaxAge(24 * 60 * 60); // 24小时
            accountCookie.setPath("/");
            response.addCookie(accountCookie);

            // 返回成功信息
            resp.put("message", result);
            resp.put("accountId", accountId);
            return ResponseEntity.ok(resp);
        } else {
            // 登录失败
            resp.put("message", result);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }

    //修改密码
    @PostMapping("/changePassword")
    public ResponseEntity<Map<String, Object>> changePassword(@RequestBody Map<String, String> credentials) {
        String accountId = credentials.get("accountId");
        String oldPassword = credentials.get("oldPassword");
        String newPassword = credentials.get("newPassword");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || oldPassword == null || newPassword == null) {
            resp.put("message", "accountId, oldPassword and newPassword are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
        }

        // 调用修改密码服务
        String result = sellerService.changePassword(accountId, oldPassword, newPassword, accountType);

        resp.put("message", result);
        if ("修改密码成功".equals(result)) {
            // 修改成功，返回成功信息
            return ResponseEntity.ok(resp);
        } else {
            // 修改失败
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }

    //提交资质
    @PostMapping("/postQualificationContent")
    public ResponseEntity<Map<String, Object>> postQualificationContent(@RequestBody Map<String, String> credentials) {
        String accountId = credentials.get("accountId");
        String qualificationContent = credentials.get("qualificationContent");

        Map<String, Object> resp = new HashMap<>();
        // 验证必要参数
        if (accountId == null || qualificationContent == null) {
            resp.put("message", "accountId and qualificationContent are required");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(resp);
        }

        // 调用提交资质服务
        String result = sellerService.postQualificationContent(accountId, qualificationContent, accountType);

        resp.put("message", result);
        if ("提交资质成功".equals(result)) {
            // 提交成功，返回成功信息
            return ResponseEntity.ok(resp);
        } else {
            // 提交失败
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(resp);
        }
    }

    //上架商品信息
    @PostMapping("/postGoodsInfo")
    public ResponseEntity<Map<String, Object>> postGoodsInfo(@RequestParam Map<String, String> credentials,@RequestParam("productImages") MultipartFile[] images) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String result = sellerService.postGoodsInfo(credentials, images);
            // 保证 message 不为 null
            resp.put("message", result == null ? "" : result);
            if ("商品信息提交成功".equals(result)) {
                // 上架成功，返回成功信息
                return ResponseEntity.ok(resp);
            } else {
                // 上架失败
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(resp);
            }
        } catch (Exception e) {
            String errMsg = e.getMessage() == null ? e.toString() : e.getMessage();
            resp.put("message", "图片上传失败: " + errMsg);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(resp);
        }
    }

    //展示已上架的信息
    @PostMapping("/showGoodsInfo")
    public ResponseEntity<Map<String, Object>> showGoodsInfo(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        try {
            List<ProductListing> products = sellerService.getAvailableProducts(credentials);
            resp.put("message", "获取成功");
            resp.put("products", products);
            return ResponseEntity.ok(resp);
        } catch (Exception e) {
            resp.put("message", "获取商品列表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resp);
        }
    }


    //修改商品信息
    @PostMapping("/updateGoodsInfo")
    public ResponseEntity<Map<String, Object>> updateGoodsInfo(@RequestParam Map<String, String> credentials,@RequestParam(value = "productImages", required = false) MultipartFile[] images) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String result = sellerService.updateGoodsInfo(credentials, images);
            resp.put("message", result == null ? "" : result);
            if ("商品更新成功".equals(result)) {
                return ResponseEntity.ok(resp);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(resp);
            }
        } catch (Exception e) {
            String errMsg = e.getMessage() == null ? e.toString() : e.getMessage();
            resp.put("message", "图片上传失败: " + errMsg);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(resp);
        }
    }


    //删除商品信息
    @PostMapping("/deleteGoodsInfo")
    public ResponseEntity<Map<String, Object>> deleteGoodsInfo(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String result = sellerService.deleteGoodsInfo(credentials);
            resp.put("message", result == null ? "" : result);
            if ("商品删除成功".equals(result)) {
                return ResponseEntity.ok(resp);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(resp);
            }
        } catch (Exception e) {
            String errMsg = e.getMessage() == null ? e.toString() : e.getMessage();
            resp.put("message", "删除失败: " + errMsg);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(resp);
        }
    }




    //展示买家订单信息
        @PostMapping("/showBuyerOrderInfo")
    public ResponseEntity<Map<String, Object>> showBuyerOrderInfo(jakarta.servlet.http.HttpServletRequest request, @RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();
        // 从Cookie中获取accountId
        String accountId = credentials.get("sellerId");
        jakarta.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (jakarta.servlet.http.Cookie cookie : cookies) {
                if ("accountId".equals(cookie.getName())) {
                    accountId = cookie.getValue();
                    break;
                }
            }
        }



        Object result = sellerService.showBuyerOrderInfo(accountId);
        resp.put("message", "查询成功");
        resp.put("data", result);
        return ResponseEntity.ok(resp);
    }

    //发货
    @PostMapping("/deliverGoods")
    public ResponseEntity<Map<String, Object>> deliverGoods(@RequestBody Map<String, String> credentials) {
        Map<String, Object> resp = new HashMap<>();

            String result = sellerService.deliverGoods(credentials);
            resp.put("message", result);
            if ("发货成功".equals(result)) {
                return ResponseEntity.ok(resp);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(resp);
            }

    }

    //售后
//    @PostMapping("/afterSale")
//    public ResponseEntity<?> afterSale(@RequestBody Map<String, String> credentials) {
//        String result = sellerService.afterSale(credentials);
//        if ("售后成功".equals(result)) {
//            return ResponseEntity.ok(result);
//        } else {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
//                    .body(result);
//        }
//    }

}